package com.mcflywzx.airhockey;

import com.mcflywzx.airhockey.util.Tools;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ConfigurationInfo;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Toast;

public class AirHockeyActivity extends Activity {
	private GLSurfaceView glSurfaceView;
	private boolean rendererSet = false;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        glSurfaceView = new GLSurfaceView(this); 
        
        final ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
        final AirHockeyRenderer AHR = new AirHockeyRenderer(this);

        if(Tools.CanGLES2(configurationInfo)){//平台验证
        	//
        	glSurfaceView.setEGLContextClientVersion(2);
        	glSurfaceView.setRenderer(AHR);
        	rendererSet = true;
        } else {
        	Toast.makeText(this, "这个设备不支持OpenGL ES 2.0 。", Toast.LENGTH_LONG).show();
        	return;
        }
        
        glSurfaceView.setOnTouchListener(new OnTouchListener() {
        	@Override
        	public boolean onTouch(View v, MotionEvent event) {
        		if(event != null) {
     
        			final float normalizedX = (event.getX() / (float) v.getWidth()) * 2 - 1;
        			final float normalizedY = - ((event.getY() / (float) v.getHeight()) * 2 - 1);
        		
        			if(event.getAction() == MotionEvent.ACTION_DOWN) {
        				glSurfaceView.queueEvent(new Runnable() {
        					@Override
        					public void run() {
        						AHR.TPress(normalizedX, normalizedY);
        					}
        				});
        			} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
        				glSurfaceView.queueEvent(new Runnable() {
        					@Override
        					public void run() {
        						AHR.TDrag(normalizedX, normalizedY);
        					}
        				
        			});
        			} 
        				return true;
        			} else {
        				glSurfaceView.queueEvent(new Runnable() {
        					@Override
        					public void run() {
        						AHR.NoneTouch();
        					}
        				});
        				return false;
        			}
        	}
        });
        setContentView(glSurfaceView);
    }
    
    @Override
    protected void onPause() { 
    	super.onPause();
    	
    	if (rendererSet) {
    		glSurfaceView.onPause();
    	}
    }

    @Override
    protected void onResume() {
    	super.onResume();
    	
    	if (rendererSet) {
    		glSurfaceView.onResume();
    	}
    }
}
